using System;
using ConsentManagementProviderLib.Json;
using UnityEngine;

namespace ConsentManagementProviderLib.iOS
{
	internal class CMPiOSListenerHelper : MonoBehaviour
	{
		private Action<GdprConsent> onCustomConsentsGDPRSuccessAction;

		internal GdprConsent customGdprConsent;

		internal SpConsents _spConsents;

		private void Awake()
		{
			base.gameObject.name = "CMPiOSListenerHelper";
		}

		internal void SetCustomConsentsGDPRSuccessAction(Action<GdprConsent> action)
		{
			onCustomConsentsGDPRSuccessAction = action;
		}

		private void Callback(string message)
		{
			CmpDebugUtil.Log("IOS_CALLBACK_RECEIVED: " + message);
		}

		private void OnConsentReady(string message)
		{
			CmpDebugUtil.Log("OnConsentReady IOS_CALLBACK_RECEIVED: " + message);
			SpConsents spConsents = null;
			try
			{
				spConsents = JsonUnwrapper.UnwrapSpConsents(message);
			}
			catch (Exception ex)
			{
				Debug.LogError("Something went wrong while parsing the json data; null will be returned. \n Exception message: " + ex.Message);
			}
			finally
			{
				_spConsents = spConsents;
				ConsentMessenger.Broadcast<IOnConsentReady>(new object[1] { spConsents });
			}
		}

		private void OnConsentUIReady(string message)
		{
			CmpDebugUtil.Log("OnConsentUIReady IOS_CALLBACK_RECEIVED: " + message);
			ConsentMessenger.Broadcast<IOnConsentUIReady>(new object[1] { message });
		}

		private void OnConsentAction(string message)
		{
			CmpDebugUtil.Log("OnConsentAction IOS_CALLBACK_RECEIVED: " + message);
			CONSENT_ACTION_TYPE cONSENT_ACTION_TYPE = (CONSENT_ACTION_TYPE)Convert.ToInt32(message);
			ConsentMessenger.Broadcast<IOnConsentAction>(new object[1] { cONSENT_ACTION_TYPE });
		}

		private void OnConsentUIFinished(string message)
		{
			CmpDebugUtil.Log("OnConsentUIFinished IOS_CALLBACK_RECEIVED: " + message);
			ConsentMessenger.Broadcast<IOnConsentUIFinished>(Array.Empty<object>());
		}

		private void OnErrorCallback(string jsonError)
		{
			CmpDebugUtil.LogError("OnErrorCallback IOS_CALLBACK_RECEIVED: " + jsonError);
			Exception ex = new Exception(jsonError);
			ConsentMessenger.Broadcast<IOnConsentError>(new object[1] { ex });
		}

		private void OnCustomConsentGDPRCallback(string jsonSPGDPRConsent)
		{
			CmpDebugUtil.Log("OnCustomConsentGDPRCallback IOS_CALLBACK_RECEIVED: " + jsonSPGDPRConsent);
			GdprConsent gdprConsent = null;
			try
			{
				gdprConsent = JsonUnwrapper.UnwrapGdprConsent(jsonSPGDPRConsent);
			}
			catch (Exception ex)
			{
				Debug.LogError("Something went wrong while parsing the json data; null will be returned. \n Exception message: " + ex.Message);
			}
			finally
			{
				if (gdprConsent == null)
				{
					onCustomConsentsGDPRSuccessAction?.Invoke(null);
				}
				else
				{
					customGdprConsent = gdprConsent;
					onCustomConsentsGDPRSuccessAction?.Invoke(gdprConsent);
				}
			}
		}
	}
}
